#!/bin/bash

source util.sh

hostname=$(hostname)

function get_real_ip()
{
    correct_network_ip=
    hostarr=$1
    curiparr=$2
    for(( i=0;i<${#hostarr[@]};i++))
    do
        
        for(( j=0;j<${#curiparr[@]};j++)) 
        do
            if [ "${hostarr[i]}" = "${curiparr[j]}" ]; then
                correct_network_ip="${hostarr[i]}"
            fi
        done;
    done;
    echo ${correct_network_ip}
}

function init_database()
{
    # init datanode with parameters
    gs_initdb -D ${datanode_dir} --nodename=nodename -w ${DEFAULT_PASSWD}

    #close mot
    echo "enable_numa = false" >> ${datanode_dir}/mot.conf 
    echo "------------- set guc -------${primaryhost}  ---${standbyhost}-------"
    curips=$(ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:")
    echo "$curips"
    hostarr=(${primaryhost})
    standby_hosts=${standbyhost}
    hostarr+=(${standby_hosts//,/ })
    curiparr=(${curips// / })

    correct_network_ip=`get_real_ip $hostarr $curiparr`

    index=1
    for(( i=0;i<${#hostarr[@]};i++)) 
    do
        if [ "${correct_network_ip}" != "${hostarr[i]}" ]; then
            echo "----------- index $i, ${hostarr[i]}"
            gs_guc set -D ${datanode_dir} -c "replconninfo${index}='localhost=${correct_network_ip} localport=5433 localheartbeatport=5436 remotehost=${hostarr[i]} remoteport=5433 remoteheartbeatport=5436'"
            index=$(expr $index + 1)
        fi
        gs_guc set -D ${datanode_dir} -h "host all all ${hostarr[i]}/32 trust"
    done;

    gs_guc set -D ${datanode_dir} -c "remote_read_mode=off";
    gs_guc set -D ${datanode_dir} -c "replication_type=1";
    gs_guc set -D ${datanode_dir} -c "port=5432";
    gs_guc set -D ${datanode_dir} -c "listen_addresses='*'";

}

function generate_static_config_file()
{
    if [ -f ${GAUSSHOME}/bin/cluster_static_config ]; then
        rm ${GAUSSHOME}/bin/cluster_static_config
    fi
    gs_om -t generateconf -X /home/omm/cluster.xml
    if [ $? -ne 0 ]; then
        echo "generate static config file failed..."
        exit 1
    fi
    cp /opengauss/cluster/tool/script/static_config_files/cluster_static_config_${hostname} ${GAUSSHOME}/bin/cluster_static_config
}

function get_nodeid()
{
    nodeid=-1
    c=0
    for line in `cm_ctl view`
    do
        account=$line
        accounts[$c]=$account
        if [ "$account" == "nodeName:$hostname" ]; then
            string=${accounts[$c-1]}
            array=(${string//\:/ })
            nodeid=${array[-1]}
            break
        fi
        ((c++))
    done
    echo "######################### $hostname=$nodeid ##################"
    return $nodeid
}

function init_cm_config()
{
    # touch ${GAUSSHOME}/bin/cluster_manual_start
    cp ${GAUSSHOME}/share/config/cm_server.conf.sample ${cm_config_path}/cm_server/cm_server.conf
    cp ${GAUSSHOME}/share/config/cm_agent.conf.sample ${cm_config_path}/cm_agent/cm_agent.conf
    if [ ! -d $GAUSSHOME/share/sslcert/cm ]; then
        mkdir $GAUSSHOME/share/sslcert/cm
    fi
    get_nodeid
    nodeid=$?
    if [ $nodeid == -1 ]; then
        echo "could not found nodeid of ${hostname}"
        exit 1
    fi
    cmserver_log=${GAUSSLOG}/cm/cm_server
    cmagent_log=${GAUSSLOG}/cm/cm_agent
    cm_ctl set --param --server -k log_dir="'${cmserver_log}'" -n $nodeid
    cm_ctl set --param --agent -k log_dir="'${cmagent_log}'" -n $nodeid
    cm_ctl set --param --agent -k unix_socket_directory="'$GAUSSHOME'" -n $nodeid
}

# expect_encrypt "cmd" "password" "success info"
function expect_encrypt()
{
        /usr/bin/expect <<-EOF
        set timeout -1
        spawn $1
        expect {
                "*yes/no" { send "yes\r"; exp_continue }
                "*password:" { send "$2\r"; exp_continue }
                "*password again:" { send "$2\r"; exp_continue }
                "*$3*" { exit }
        }
        expect eof
EOF
        if [ $? == 0 ]
        then
            return 0
        else
            return 1
        fi
}

function expect_createtrust()
{
        /usr/bin/expect <<-EOF
        set timeout -1
        spawn $1
        expect {
                "Password:" { send "$2\r"; exp_continue }
                "*$3*" { exit }
        }
        expect eof
EOF
        if [ $? == 0 ]
        then
            return 0
        else
            return 1
        fi
}

function generate_cm_cert()
{
    client_cmd="cm_ctl encrypt -M client -D $GAUSSHOME/share/sslcert/cm"
    server_cmd="cm_ctl encrypt -M server -D $GAUSSHOME/share/sslcert/cm"
    expect_encrypt "${client_cmd}" "${DEFAULT_PASSWD}" "encrypt success."
    expect_encrypt "${server_cmd}" "${DEFAULT_PASSWD}" "encrypt success."
}

function create_user_trust()
{
    cp ${app_path}/bin/encrypt ${tool_path}/script/gspylib/clib/

    # create trust
    expect_createtrust "python3 ${tool_path}/script/gs_createtrust.py -f /home/omm/hostfile -l create_trust.log" $DEFAULT_PASSWD "Successfully created SSH trust"
    if [ $? -eq 0 ]; then
        echo "Create user trust successfully..."
    else
        echo "Create user trust failed..."
    fi
}

function main()
{
    source ${ENVFILE}
    init_database
    generate_static_config_file
    init_cm_config
    generate_cm_cert
    
    nohup $GAUSSHOME/bin/om_monitor -L $GAUSSLOG/cm/om_monitor &
    create_user_trust
    
    # 启动完成后，如果互信还有问题，等待几个节点都ping通，再去创建
    # 启动完成后，如果主机角色没有切换到配置的主机上面，需要坐下主动切换
    # cm_ctl switchover -n 1 -D /opengauss/cluster/datanode/dn1/
}


main $@